package com.kara.dao.impl;

import java.util.List;

import org.appfuse.dao.hibernate.GenericDaoHibernate;
import org.appfuse.model.User;
import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.kara.dao.ClazzDao;
import com.kara.entity.Clazz;
import com.kara.entity.SchoolYear;
import com.kara.entity.Trinn;



@Repository("clazzDao")
public class ClazzDaoImpl extends GenericDaoHibernate<Clazz, Long> implements ClazzDao{

	@Autowired
	SessionFactory sessionFactory;
	
	public ClazzDaoImpl() {
		super(Clazz.class);
	}
	public ClazzDaoImpl(Class<Clazz> persistentClass) {
		super(persistentClass);
	}

	public List<User> getTeachers() {
		List <User> teachers = getHibernateTemplate().find(" teachers from class ");
		User mainTeacher = getMainTeacher();
		
		if (teachers.contains(mainTeacher)){
			throw new IllegalStateException("Main teacher is included with other teachers., main teacherUserName:<"+mainTeacher.toString()+">");
		}
		return teachers;
	}

	public User getMainTeacher() {
		User mainTeacher = (User) getHibernateTemplate().find(" mainTeacher from class " );
		
		return mainTeacher;
	}

	public Clazz saveClazz(Clazz clazz) {
		getHibernateTemplate().saveOrUpdate(clazz);
		getHibernateTemplate().flush();
		return clazz;
	}

	@SuppressWarnings("unchecked")
	public List<Clazz> getClazz(Trinn trinn) {
		
		String query = " from Clazz c where c.trinn = :trinn";
		return getHibernateTemplate().findByNamedParam(query, "trinn", trinn);

	}
	@SuppressWarnings("unchecked")
	public List<Clazz> getClazz(SchoolYear schoolYear) {
		
		String query = " from Clazz c where c.schoolYear.id = :id";
		
		return getHibernateTemplate().findByNamedParam(query, "id", schoolYear.getId());
		
	}

	
}
